﻿using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows.Forms;
using NppPluginNET;
using SCH_Tools;
using SCH_Tools.Forms;

namespace SCH_Tools
{
    class Main
    {
        #region " Fields "
        internal const string PluginName = "SCH_Tools";
        static string iniFilePath = null;
        static bool someSetting = false;

        //Dialog Base
        static frmMyDlg frmMyDlg = null;
        static int idMyDlg = -1;
        //Dialog Database
        static frmAdminDataBase frmDataBaseAdmin = null;
        static int idDataBaseAdmin = -1;
        //Dialog Database
        static frmGridData frmDataBaseFill = null;
        static int idDataBaseFill = -1;

        static Bitmap tbBmp = Properties.Resources.Yellow_tag;
        static Bitmap tbBmp_tbTab = Properties.Resources.Yellow_tag;

        static Bitmap tbBmpDataBase = Properties.Resources.database;
        static Bitmap tbBmpDataBase_tbTab = Properties.Resources.database;

        static Icon tbIcon = null;
        #endregion

        #region " StartUp/CleanUp "
        internal static void CommandMenuInit()
        {
            StringBuilder sbIniFilePath = new StringBuilder(Win32.MAX_PATH);
            Win32.SendMessage(PluginBase.nppData._nppHandle, NppMsg.NPPM_GETPLUGINSCONFIGDIR, Win32.MAX_PATH, sbIniFilePath);
            iniFilePath = sbIniFilePath.ToString();
            if (!Directory.Exists(iniFilePath)) Directory.CreateDirectory(iniFilePath);
            iniFilePath = Path.Combine(iniFilePath, PluginName + ".ini");
            someSetting = (Win32.GetPrivateProfileInt("SomeSection", "SomeKey", 0, iniFilePath) != 0);

            PluginBase.SetCommand(0, "MyMenuCommand", myMenuFunction, new ShortcutKey(false, false, false, Keys.None));
            PluginBase.SetCommand(1, "MyDockableDialog", myDockableDialog); idMyDlg = 1;
            PluginBase.SetCommand(2, "MyDataBaseDialog", myDataBaseDialog); idDataBaseAdmin = 2;
        }
        internal static void SetToolBarIcon()
        {
            toolbarIcons tbIcons = new toolbarIcons();
            tbIcons.hToolbarBmp = tbBmpDataBase.GetHbitmap();
            IntPtr pTbIcons = Marshal.AllocHGlobal(Marshal.SizeOf(tbIcons));

            Marshal.StructureToPtr(tbIcons, pTbIcons, false);
            Win32.SendMessage(PluginBase.nppData._nppHandle, NppMsg.NPPM_ADDTOOLBARICON, PluginBase._funcItems.Items[idDataBaseAdmin]._cmdID, pTbIcons);
            Marshal.FreeHGlobal(pTbIcons);
        }
        internal static void PluginCleanUp()
        {
            Win32.WritePrivateProfileString("SomeSection", "SomeKey", someSetting ? "1" : "0", iniFilePath);
        }
        #endregion

        #region " Menu functions "
        internal static void myMenuFunction()
        {
            MessageBox.Show("dddd");
        }
        internal static void myDockableDialog()
        {
            if (frmMyDlg == null)
            {
                frmMyDlg = new frmMyDlg();

                using (Bitmap newBmp = new Bitmap(16, 16))
                {
                    Graphics g = Graphics.FromImage(newBmp);
                    ColorMap[] colorMap = new ColorMap[1];
                    colorMap[0] = new ColorMap();
                    colorMap[0].OldColor = Color.Fuchsia;
                    colorMap[0].NewColor = Color.FromKnownColor(KnownColor.ButtonFace);
                    ImageAttributes attr = new ImageAttributes();
                    attr.SetRemapTable(colorMap);
                    g.DrawImage(tbBmp_tbTab, new Rectangle(0, 0, 16, 16), 0, 0, 16, 16, GraphicsUnit.Pixel, attr);
                    tbIcon = Icon.FromHandle(newBmp.GetHicon());
                }

                NppTbData _nppTbData = new NppTbData();
                _nppTbData.hClient = frmMyDlg.Handle;
                _nppTbData.pszName = "My dockable dialog";
                _nppTbData.dlgID = idMyDlg;
                _nppTbData.uMask = NppTbMsg.DWS_DF_CONT_RIGHT | NppTbMsg.DWS_ICONTAB | NppTbMsg.DWS_ICONBAR;
                _nppTbData.hIconTab = (uint)tbIcon.Handle;
                _nppTbData.pszModuleName = PluginName;
                IntPtr _ptrNppTbData = Marshal.AllocHGlobal(Marshal.SizeOf(_nppTbData));
                Marshal.StructureToPtr(_nppTbData, _ptrNppTbData, false);

                Win32.SendMessage(PluginBase.nppData._nppHandle, NppMsg.NPPM_DMMREGASDCKDLG, 0, _ptrNppTbData);
            }
            else
            {
                Win32.SendMessage(PluginBase.nppData._nppHandle, NppMsg.NPPM_DMMSHOW, 0, frmMyDlg.Handle);
            }
        }
        internal static void myDataBaseDialog()
        {
            if (frmDataBaseAdmin == null)
            {
                frmDataBaseAdmin = new frmAdminDataBase();

                using (Bitmap newBmp = new Bitmap(16, 16))
                {
                    Graphics g = Graphics.FromImage(newBmp);
                    ColorMap[] colorMap = new ColorMap[1];
                    colorMap[0] = new ColorMap();
                    colorMap[0].OldColor = Color.Fuchsia;
                    colorMap[0].NewColor = Color.FromKnownColor(KnownColor.ButtonFace);
                    ImageAttributes attr = new ImageAttributes();
                    attr.SetRemapTable(colorMap);
                    g.DrawImage(tbBmpDataBase_tbTab, new Rectangle(0, 0, 16, 16), 0, 0, 16, 16, GraphicsUnit.Pixel, attr);
                    tbIcon = Icon.FromHandle(newBmp.GetHicon());
                }

                NppTbData _nppTbData = new NppTbData();
                _nppTbData.hClient = frmDataBaseAdmin.Handle;
                _nppTbData.pszName = "DataBase Administrator";
                _nppTbData.dlgID = idDataBaseAdmin;
                _nppTbData.uMask = NppTbMsg.DWS_DF_CONT_RIGHT | NppTbMsg.DWS_ICONTAB | NppTbMsg.DWS_ICONBAR;
                _nppTbData.hIconTab = (uint)tbIcon.Handle;
                _nppTbData.pszModuleName = PluginName;
                IntPtr _ptrNppTbData = Marshal.AllocHGlobal(Marshal.SizeOf(_nppTbData));
                Marshal.StructureToPtr(_nppTbData, _ptrNppTbData, false);

                Win32.SendMessage(PluginBase.nppData._nppHandle, NppMsg.NPPM_DMMREGASDCKDLG, 0, _ptrNppTbData);
            }
            else
            {
                Win32.SendMessage(PluginBase.nppData._nppHandle, NppMsg.NPPM_DMMSHOW, 0, frmDataBaseAdmin.Handle);
            }
        }
        internal static void myFillDataBaseDialog()
        {
            if (frmDataBaseFill == null)
            {
                frmDataBaseFill = new frmGridData();

                using (Bitmap newBmp = new Bitmap(16, 16))
                {
                    Graphics g = Graphics.FromImage(newBmp);
                    ColorMap[] colorMap = new ColorMap[1];
                    colorMap[0] = new ColorMap();
                    colorMap[0].OldColor = Color.Fuchsia;
                    colorMap[0].NewColor = Color.FromKnownColor(KnownColor.ButtonFace);
                    ImageAttributes attr = new ImageAttributes();
                    attr.SetRemapTable(colorMap);
                    g.DrawImage(tbBmpDataBase_tbTab, new Rectangle(0, 0, 16, 16), 0, 0, 16, 16, GraphicsUnit.Pixel, attr);
                    tbIcon = Icon.FromHandle(newBmp.GetHicon());
                }

                NppTbData _nppTbData = new NppTbData();
                _nppTbData.hClient = frmDataBaseFill.Handle;
                _nppTbData.pszName = "DataBase Fill Data";
                _nppTbData.dlgID = idDataBaseFill;
                _nppTbData.uMask = NppTbMsg.DWS_DF_CONT_RIGHT | NppTbMsg.DWS_ICONTAB | NppTbMsg.DWS_ICONBAR;
                _nppTbData.hIconTab = (uint)tbIcon.Handle;
                _nppTbData.pszModuleName = PluginName;
                IntPtr _ptrNppTbData = Marshal.AllocHGlobal(Marshal.SizeOf(_nppTbData));
                Marshal.StructureToPtr(_nppTbData, _ptrNppTbData, false);

                Win32.SendMessage(PluginBase.nppData._nppHandle, NppMsg.NPPM_DMMREGASDCKDLG, 0, _ptrNppTbData);
            }
            else
            {
                Win32.SendMessage(PluginBase.nppData._nppHandle, NppMsg.NPPM_DMMSHOW, 0, frmDataBaseFill.Handle);
            }
        }
        #endregion

        #region "Funtions Internal"
        /// <summary>
        /// Set Server and get result of SQL Statement selected in document
        /// </summary>
        public static void RunFiles(bool onlySelected)
        {
            string sqlStatement = string.Empty;
            myFillDataBaseDialog();

            if (onlySelected)
            {
                sqlStatement = GetTextDocumentSelected();
            }
            else
            {
                sqlStatement = GetTextDocument();
            }

            if (!string.IsNullOrEmpty(sqlStatement))
            {
                frmDataBaseFill.ExecuteSqlStatement(frmDataBaseAdmin.GetServerSelected(), sqlStatement);
            }
            else
            {
                MessageBox.Show(@"SQL Statement not found!!!");
            }
        }

        /// <summary>
        /// Set Server and run massive files in current directory
        /// </summary>
        public static void RunMassiveFiles()
        {
            myFillDataBaseDialog();
            frmDataBaseFill.ExecuteSqlFiles(frmDataBaseAdmin.GetServerSelected(), frmDataBaseAdmin.FilesFound, string.Empty, frmDataBaseAdmin.Driver, (frmDataBaseAdmin.ActiveOutput ? frmDataBaseAdmin.PathOutput : string.Empty));
        }
        #endregion

        #region "Functions Personalize NPP"
        /// <summary>
        /// Get File Name of Document Active
        /// </summary>
        /// <returns></returns>
        public static string GetFileDocument()
        {
            NppMsg msg = NppMsg.NPPM_GETFULLCURRENTPATH;
            StringBuilder path = new StringBuilder(Win32.MAX_PATH);
            Win32.SendMessage(PluginBase.nppData._nppHandle, msg, 0, path);
            return path.ToString();
        }
        /// <summary>
        /// Get text document active
        /// </summary>
        /// <returns></returns>
        public static string GetTextDocument()
        {
            int length = (int)Win32.SendMessage(PluginBase.GetCurrentScintilla(), SciMsg.SCI_GETLENGTH, 0, 0) + 1;
            StringBuilder sb = new StringBuilder(length);
            Win32.SendMessage(PluginBase.GetCurrentScintilla(), SciMsg.SCI_GETTEXT, length, sb);
            return sb.ToString();
        }
        /// <summary>
        /// Get text selected in document active
        /// </summary>
        /// <returns></returns>
        public static string GetTextDocumentSelected()
        {
            int lengthSEL = (int)Win32.SendMessage(PluginBase.GetCurrentScintilla(), SciMsg.SCI_GETLENGTH, 0, 0) + 1;
            StringBuilder sbSel = new StringBuilder(lengthSEL);
            Win32.SendMessage(PluginBase.GetCurrentScintilla(), SciMsg.SCI_GETSELTEXT, lengthSEL, sbSel);
            return sbSel.ToString();
        }
        #endregion
    }
}